package com.qyhl.module_activities.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.request.RequestOptions;
import com.library.OnPopupItemClickListener;
import com.library.PopupView;
import com.luck.picture.lib.tools.ScreenUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.module_activities.R;
import com.qyhl.module_activities.act.signup.SignUpActActivity;
import com.qyhl.module_activities.utils.inter.ActCheckBoxCallBack;
import com.qyhl.module_activities.utils.inter.ActImageCallBack;
import com.qyhl.module_activities.utils.inter.ActPopupCallBack;
import com.qyhl.module_activities.utils.inter.ActRadioButtonCallBack;
import com.qyhl.module_activities.utils.inter.ActVideoCallBack;
import com.qyhl.module_activities.utils.view.FlowRadioGroup;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.act.ActivityViewOptionBean;
import com.qyhl.webtv.commonlib.entity.act.PlayerViewResultBean;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.bumptech.glide.load.resource.bitmap.VideoDecoder.FRAME_OPTION;
import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoCover;
import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoUrl;


/**
 * Created  on 2017/12/25.
 *
 * @author helin
 * 活动View管理
 */
public class ViewUtils {

    static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 选手报名信息
     *
     * @param context
     * @param bean
     * @return
     */
    public static View createShowView(final Activity context, PlayerViewResultBean bean, ViewGroup viewGroup) {
        if (bean.getIsShow() == 3) {
            //报名图，不显示
            return null;
        }

        final String result = bean.getResultText();
        View view = context.getLayoutInflater().inflate(R.layout.act_player_results_text_view, viewGroup, false);
        TextView title = view.findViewById(R.id.player_view_title);

        if (bean.getType().equals("input") || bean.getType().equals("textarea")) {
            title.setText(bean.getViewText() + ":  " + result);

        } else if (bean.getType().equals("image")) {
            ImageView image = view.findViewById(R.id.player_view_image);
            title.setText(bean.getViewText() + ":  ");
            image.setVisibility(View.VISIBLE);
            Glide.with(context)
                    .load(result)
                    .apply(new RequestOptions().error(R.drawable.icon_live_no_img))
                    .into(image);
            image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ArrayList<String> lists = new ArrayList<>();
                    lists.add(result);
                    MNImageBrowser.showImageBrowser(context, v, 1, lists);
                }
            });

        } else if (bean.getType().equals("video")) {
            title.setText(bean.getViewText() + ":  ");
            view.findViewById(R.id.videoLayout).setVisibility(View.VISIBLE);
            RoundedImageView image = view.findViewById(R.id.player_video);
            if (StringUtils.isEmpty(bean.getVideoCover())) {
                loadVideoScreenshot(context, result, image, 1000);

                view.findViewById(R.id.player_video_go).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString(IntentKey_VideoUrl, result);
                        bundle.putString(IntentKey_VideoCover, "");
                        RouterManager.router(ARouterPathConstant.VIDEO_EMPTY_CONTROL, bundle);

                    }
                });
            } else {
                Glide.with(context).load(bean.getVideoCover()).apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default)).into(image);

                view.findViewById(R.id.player_video_go).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString(IntentKey_VideoUrl, result);
                        bundle.putString(IntentKey_VideoCover, bean.getVideoCover());
                        RouterManager.router(ARouterPathConstant.VIDEO_EMPTY_CONTROL, bundle);

                    }
                });
            }

        }

        return view;
    }


    public static void loadVideoScreenshot(final Context context, String uri, ImageView imageView, long frameTimeMicros) {
        RequestOptions requestOptions = RequestOptions.frameOf(frameTimeMicros);
        requestOptions.set(FRAME_OPTION, MediaMetadataRetriever.OPTION_CLOSEST);
        requestOptions.transform(new BitmapTransformation() {
            @Override
            protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
                return toTransform;
            }

            @Override
            public void updateDiskCacheKey(MessageDigest messageDigest) {
                try {
                    messageDigest.update((context.getPackageName() + "RotateTransform").getBytes("utf-8"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        Glide.with(context).load(uri).apply(requestOptions).into(imageView);
    }


    /**
     * 单行输入控件
     */
    public static View createInputView(Activity context, ViewGroup pgroup, String ti, String hint, int isRe, int index) {
        View view = context.getLayoutInflater().inflate(R.layout.act_item_act_input_view, pgroup, false);
        TextView te = view.findViewById(R.id.sign_act_text);
        TextView re = (TextView) view.findViewById(R.id.is_required);
        EditText ed = (EditText) view.findViewById(R.id.sign_act_edit);
        //是否必填
        if (isRe == 1) {
            re.setVisibility(View.VISIBLE);
        }
        te.setText(ti);
        ed.setHint(hint);
        return view;
    }


    /**
     * 创建图片作品集
     */
    public static View createImageWorkView(Activity context, LinearLayout pgroup, String viewText, String descri, Integer isRe, SignUpActActivity.RecyclerViewAdatper adatper, int index) {
        View view = context.getLayoutInflater().inflate(R.layout.act_item_act_imgwork_view, pgroup, false);
        TextView picture_works_text = (TextView) view.findViewById(R.id.picture_works_text);
        picture_works_text.setText(viewText);
        TextView description = (TextView) view.findViewById(R.id.description);
        if (measureText(picture_works_text, description, viewText, descri, ScreenUtils.getScreenWidth(context))) {
            description.setText(descri);
        } else {
            description.setVisibility(View.GONE);
        }

        TextView is_required = (TextView) view.findViewById(R.id.is_required);
        //是否必填
        if (isRe == 1) {
            is_required.setVisibility(View.VISIBLE);
        }
        RecyclerView sign_act_works_image = (RecyclerView) view.findViewById(R.id.sign_act_works_image);
        sign_act_works_image.setLayoutManager(new GridLayoutManager(context, 3));
        sign_act_works_image.setAdapter(adatper);
        return view;
    }

    /**
     * 创建时间旋转器
     *
     * @param context
     * @param ti      提示信息
     * @param isRe    是否必填
     * @param index   位置
     * @return
     */
    public static View createDateTimeView(final Activity context, ViewGroup pgroup, String ti, int isRe, int index) {
        View view = context.getLayoutInflater().inflate(R.layout.act_item_act_time_view, pgroup, false);
        TextView te = (TextView) view.findViewById(R.id.sign_act_text);
        TextView re = (TextView) view.findViewById(R.id.is_required);
        final TextView timeText = (TextView) view.findViewById(R.id.text_time);
        te.setText(ti);
        if (isRe == 1) {
            re.setVisibility(View.VISIBLE);
        }

        timeText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(timeText.getWindowToken(), 0);
                showTimePicker(context, timeText);
            }
        });
        return view;
    }

    /**
     * 展示时间选择器
     *
     * @param context
     * @param timeView
     */
    private static void showTimePicker(Context context, final TextView timeView) {
        TimePickerView pvTime = new TimePickerBuilder(context, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String dateTime = simpleDateFormat.format(date);
                timeView.setText(dateTime);
            }
        }).build();
        pvTime.show();
    }

    /***
     * 图片选择控件
     * @param context
     * @param ti
     * @param isRe
     * @param index
     * @return
     */
    public static View createImageView(Activity context, ViewGroup pgroup, String ti, String hint, int isRe, final int index, final ActImageCallBack callBack) {
        View view = context.getLayoutInflater().inflate(R.layout.act_item_act_image_view, pgroup, false);
        TextView te = (TextView) view.findViewById(R.id.sign_act_image_text);
        TextView re = (TextView) view.findViewById(R.id.is_required);
        TextView sign_act_image_describe = (TextView) view.findViewById(R.id.sign_act_image_describe);


        ImageView image = (ImageView) view.findViewById(R.id.act_sign_image);
        ImageView imageDel = (ImageView) view.findViewById(R.id.act_sign_del);
        image.setTag(R.id.act_image_tag, index);
        imageDel.setTag(R.id.act_image_tag, index);
        //图片选择
        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = Integer.parseInt(v.getTag(R.id.act_image_tag).toString());
                callBack.choiceImage(index);
            }
        });
        //图片删除
        imageDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = Integer.parseInt(v.getTag(R.id.act_image_tag).toString());
                callBack.deleteImage(index);
            }
        });


        //是否必填
        if (isRe == 1) {
            re.setVisibility(View.VISIBLE);
        }
        te.setText(ti);
        if (measureText(te, sign_act_image_describe, ti, hint, ScreenUtils.getScreenWidth(context))) {
            sign_act_image_describe.setText(hint);
        } else {
            sign_act_image_describe.setVisibility(View.GONE);
        }

        return view;
    }

    /***
     * 视频选择控件
     * @param context
     * @param ti
     * @param isRe
     * @return
     */
    public static View createVideoView(Activity context, ViewGroup pgroup, String ti, String hint, int isRe,final int index, final ActVideoCallBack callBack) {
        View view = context.getLayoutInflater().inflate(R.layout.act_item_act_video_view, pgroup, false);
        TextView te = (TextView) view.findViewById(R.id.sign_act_video_text);
        TextView re = (TextView) view.findViewById(R.id.is_required);
        TextView sign_act_video_describe = (TextView) view.findViewById(R.id.sign_act_video_describe);


        ImageView image = (ImageView) view.findViewById(R.id.act_sign_video);
        ImageView imageDel = (ImageView) view.findViewById(R.id.act_sign_del);
        image.setTag(R.id.act_video_tag, index);
        imageDel.setTag(R.id.act_video_tag, index);
        //视频选择
        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int index = Integer.parseInt(v.getTag(R.id.act_video_tag).toString());
                callBack.choiceVideo(index);
            }
        });
        //视频删除
        imageDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callBack.deleteVideo(index);
            }
        });


        //是否必填
        if (isRe == 1) {
            re.setVisibility(View.VISIBLE);
        }
        te.setText(ti);
        if (measureText(te, sign_act_video_describe, ti, hint, ScreenUtils.getScreenWidth(context))) {
            sign_act_video_describe.setText(hint);
        } else {
            sign_act_video_describe.setVisibility(View.GONE);
        }

        return view;
    }


    /**
     * 多行输入框
     *
     * @param context
     * @param ti
     * @param hint
     * @param isRe
     * @return
     */
    public static View createMultiInputView(Activity context, ViewGroup pgroup, String ti, String hint, int isRe, int index) {
        View view = context.getLayoutInflater().inflate(R.layout.act_item_act_multi_input_view, pgroup, false);

        TextView te = (TextView) view.findViewById(R.id.sign_act_multi);
        EditText ed = (EditText) view.findViewById(R.id.sign_act_multi_edit);
        TextView re = (TextView) view.findViewById(R.id.is_required);
        //是否必填
        if (isRe == 1) {
            re.setVisibility(View.VISIBLE);
        }
        te.setText(ti);
        ed.setHint(hint);

        return view;
    }


    /**
     * 单选框控件
     *
     * @param context
     * @param te
     * @param viewOptions
     * @param isRe
     * @return
     */
    public static View createRadio(Activity context, ViewGroup pgroup, String te, List<ActivityViewOptionBean> viewOptions, int isRe, int index, String dis, final ActRadioButtonCallBack callBack) {
        View view = context.getLayoutInflater().inflate(R.layout.act_item_act_radio_view, pgroup, false);
        RadioGroup group = (RadioGroup) view.findViewById(R.id.sign_radio_group);
        TextView re = (TextView) view.findViewById(R.id.is_required);
        TextView sign_radio_describe = (TextView) view.findViewById(R.id.sign_radio_describe);

        TextView text = (TextView) view.findViewById(R.id.sign_radio_text);
        text.setText(te);

        if (measureText(text, sign_radio_describe, te, dis, ScreenUtils.getScreenWidth(context))) {
            sign_radio_describe.setText(dis);
        } else {
            sign_radio_describe.setVisibility(View.GONE);
        }

        for (int i = 0; i < viewOptions.size(); i++) {
            ActivityViewOptionBean option = viewOptions.get(i);
            RadioButton radioButton = new RadioButton(context);
            radioButton.setText(option.getOptionName());
            radioButton.setButtonDrawable(ContextCompat.getDrawable(context, R.drawable.sigin_radio_button));
            radioButton.setPadding(5, 8, 0, 8);
            radioButton.setTag(index);
            radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    int index = Integer.parseInt(buttonView.getTag().toString());
                    callBack.onRadioCheck(index, buttonView.getText().toString(), isChecked);
                }
            });

            group.addView(radioButton);
        }

        //是否必填
        if (isRe == 1) {
            re.setVisibility(View.VISIBLE);
        }
        return view;
    }

    /**
     * 多选控件
     *
     * @param context
     * @param te
     * @param viewOptions
     * @param isRe
     * @return
     */
    public static View createCheckBox(Activity context, ViewGroup pgroup, String te, List<ActivityViewOptionBean> viewOptions, int isRe, int index, String dis, final ActCheckBoxCallBack checkBoxCallBack) {
        View view = context.getLayoutInflater().inflate(R.layout.act_item_act_checkbox_view, pgroup, false);
        TextView textView = (TextView) view.findViewById(R.id.sign_check_text);
        TextView re = (TextView) view.findViewById(R.id.is_required);
        TextView sign_check_describe = (TextView) view.findViewById(R.id.sign_check_describe);

        FlowRadioGroup fixGridLayout = (FlowRadioGroup) view.findViewById(R.id.check_boxs);
        textView.setText(te);
        if (measureText(textView, sign_check_describe, te, dis, ScreenUtils.getScreenWidth(context))) {
            sign_check_describe.setText(dis);
        } else {
            sign_check_describe.setVisibility(View.GONE);
        }
        for (int i = 0; i < viewOptions.size(); i++) {
            ActivityViewOptionBean option = viewOptions.get(i);
            CheckBox checkBox = new CheckBox(context);
            checkBox.setLayoutParams(new RadioGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            checkBox.setText(option.getOptionName());
            checkBox.setTag(index);
            checkBox.setPadding(5, 0, 0, 0);
            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    int index = Integer.parseInt(buttonView.getTag().toString());
                    boolean chek = checkBoxCallBack.onCheck(index, buttonView.getText().toString(), isChecked);
                    if (!chek) {
                        buttonView.setChecked(false);
                    }
                }
            });
            fixGridLayout.addView(checkBox);
        }
        //是否必填
        if (isRe == 1) {
            re.setVisibility(View.VISIBLE);
        }
        return view;
    }

    public static View createPopupView(Activity context, ViewGroup pgroup, String viewText, List<ActivityViewOptionBean> viewOptions, Integer isRe, int index, final ActPopupCallBack actPopupCallBack) {
        View view = context.getLayoutInflater().inflate(R.layout.act_item_act_popup_view, pgroup, false);
        TextView re = (TextView) view.findViewById(R.id.is_required);
        //是否必填
        if (isRe == 1) {
            re.setVisibility(View.VISIBLE);
        }
        TextView sign_text = (TextView) view.findViewById(R.id.sign_text);
        sign_text.setText(viewText);

        final PopupView popup = (PopupView) view.findViewById(R.id.popup);
        popup.setTag(index);
        List<String> list = new ArrayList<>();
        for (int i = 0; i < viewOptions.size(); i++) {
            list.add(viewOptions.get(i).getOptionName());
        }
        popup.setItemsFromList(list);
        popup.setOnItemClickListener(new OnPopupItemClickListener() {
            @Override
            public void onItemClickListener(int i, int i1, String s) {
                int index = (int) popup.getTag();
                actPopupCallBack.onPopupCheck(index, s);
            }
        });
        actPopupCallBack.onPopupCheck(index, viewOptions.get(0).getOptionName());
        return view;
    }

    private static boolean measureText(TextView text, TextView describe, String te, String dis, int screenWidth) {
        TextPaint painttext = text.getPaint();
        TextPaint paintdescribe = describe.getPaint();
        if ((painttext.measureText(te) + paintdescribe.measureText(dis)) < screenWidth) {
            return true;
        }
        return false;
    }
}
